package com.woniu.teachmall04.service;

import com.woniu.teachmall04.entity.Admin;
import com.woniu.teachmall04.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
public class AdminService {
    @Autowired
    private AdminMapper adminMapper;

    // 管理员登录
    public Admin login(String account, String password, String ip) {
        Admin admin = adminMapper.selectByAccount(account);
        if(admin == null || admin.getStatus() != 1) {
            return null;
        }

        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if(admin.getPassword().equals(encryptedPassword)) {
            // 更新登录信息
            admin.setLastLoginTime(new Date());
            admin.setLastLoginIp(ip);
            adminMapper.update(admin);
            return admin;
        }
        return null;
    }

    // 获取所有管理员
    public List<Admin> getAllAdmins() {
        return adminMapper.selectAll();
    }

    // 添加管理员
    public boolean addAdmin(Admin admin) {
        // 检查账号是否已存在
        if(adminMapper.selectByAccount(admin.getAccount()) != null) {
            return false;
        }

        // 密码加密
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        admin.setStatus(1); // 默认启用
        return adminMapper.insert(admin) > 0;
    }

    // 更新管理员信息
    public boolean updateAdmin(Admin admin) {
        Admin existing = adminMapper.selectByAccount(admin.getAccount());
        if(existing != null && !existing.getId().equals(admin.getId())) {
            return false; // 账号已存在
        }

        if(admin.getPassword() != null && !admin.getPassword().isEmpty()) {
            admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        } else {
            // 不更新密码
            admin.setPassword(null);
        }
        return adminMapper.update(admin) > 0;
    }

    // 禁用/启用管理员
    public boolean toggleAdminStatus(Integer id, Integer status) {
        return adminMapper.updateStatus(id, status) > 0;
    }

    // 删除管理员(逻辑删除)
    public boolean deleteAdmin(Integer id) {
        return adminMapper.deleteById(id) > 0;
    }
}